#!/usr/bin/env python

from __future__ import print_function

import os
import subprocess
import tempfile

def cmdsub(args, **kwargs):
    print("++ " + args)
    child = subprocess.Popen(args, stdout=subprocess.PIPE, **kwargs)
    data = child.communicate()[0].rstrip()
    print("+ " + data)
    assert child.returncode is not None
    if child.returncode != 0:
        raise CalledProcessError(child.returncode, args)
    return data

def sheval(args):
    return cmdsub("echo " + args, shell=True)

def joinargs(*arglists):
    return " ".join(arglists)

def mktemp():
    fd, path = tempfile.mkstemp(text=False)
    os.close(fd)
    return path

def chkcall(*args):
    args = joinargs(*args)
    print("+ " + subprocess.list2cmdline(args))
    subprocess.check_call(subprocess.list2cmdline(args), shell=True)

args = object()

CFLAGS = '-g -O0 -Wall -Wshadow -Wfloat-equal -ftrapv'# -fverbose-asm -save-temps'
PROJ_CFLAGS = joinargs(sheval("$(getconf LFS_CFLAGS) -std=gnu99 -D_GNU_SOURCE"), CFLAGS)
FUSE_CFLAGS = sheval("$(pkg-config --cflags fuse) -DFUSE_USE_VERSION=28")
FUSE_LDFLAGS = sheval("$(pkg-config --libs fuse)")
libcpfs_objs = []
for src in ("cpfs.c", "log.c"):
    obj = mktemp()
    libcpfs_objs.append(obj)
    chkcall("cc -o {obj} -c {src} {PROJ_CFLAGS}".format(**locals()))
libcpfs_a = mktemp()
chkcall(joinargs("ar rcs", libcpfs_a, *libcpfs_objs))
chkcall("cc -o mount.cpfs mount.cpfs.c cpfsfuse.c", libcpfs_a, FUSE_CFLAGS, PROJ_CFLAGS, FUSE_LDFLAGS, PROJ_LDFLAGS)
